﻿using AnlianCommon.Common.Domains.OrganizationalUnits;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AnlianCommon.API.Commands.AccountingUnites
{
    public class AccountingUnitQueryHandler : IRequestHandler<AccountingUnitQueryCommand, Result>
    {
        private readonly IBaseRepository<AccountingUnit> _accountingUnitRepository;

        public AccountingUnitQueryHandler(IBaseRepository<AccountingUnit> accountingUnitRepository)
        {
            _accountingUnitRepository = accountingUnitRepository;
        }
        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>

        public async Task<Result> Handle(AccountingUnitQueryCommand request, CancellationToken cancellationToken)
        {
            //返回的响应码
            var result = new Result() { Code =(int)CommonErrorCode.Search};
            try
            {
                //查询核算单元表信息 条件 父级ID  PID
                var accountingUnits = await (await _accountingUnitRepository.GetAll()).Where(c => c.Pid == 0).ToListAsync();
                //实例化级联数据源
                List<Cascard> cascards = new List<Cascard>();
                //历遍核算查到的核算单元信息
                foreach (var item in accountingUnits)
                {
                    //实例化级联数据源
                    Cascard cascard = new Cascard();
                    cascard.label = item.AccountingUnitName;//把核算单元Name赋值给级联数据源里的Label
                    cascard.value = item.AccountingUnitId;//把核算单元ID赋值给级联数据源里的Value
                    cascard.children =await GetCascards(item.AccountingUnitId);
                    cascards.Add(cascard);
                }
                result.Data = cascards;
                
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
        public async Task<List<Cascard>> GetCascards(int pid =0)
        {
            var list = await (await _accountingUnitRepository.GetAll()).Where(c => c.Pid == pid).ToListAsync();
            List<Cascard> cascards = new List<Cascard>();
            foreach (var item in list)
            {
                Cascard cascard = new Cascard();
                cascard.label = item.AccountingUnitName;
                cascard.value = item.AccountingUnitId;
                cascard.children =await GetCascards(item.AccountingUnitId);
                cascards.Add(cascard);
            }
            return cascards;
        }
    }
}
